//
//  LSPopView.swift
//  新浪微博---01次
//
//  Created by 李宗帅 on 16/5/10.
//  Copyright © 2016年 LS. All rights reserved.
//

import UIKit
import pop
class LSPopView: UIView {
    
    //父控制器
    var target: UIViewController?
    
    private lazy var buttons:[UIButton] = [UIButton]()

    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        
        self.frame.size = CGSizeMake(UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height)
        
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI(){
        backgroundColor = UIColor.yellowColor()
        
        addSubview(bgImageView)
        //添加一个按钮,用于测试
        
        addChildButtons()

        
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.snp_edges)
        }
    }
    
    private func addChildButtons() {
        

        
        //循环布局 列
        let maxClo: CGFloat = 3
        
        //按钮的宽高
        let btnW: CGFloat = 80
        let btnH: CGFloat = 110
        
        //间距
        let margin: CGFloat = (kUIScreenW - (btnW * maxClo)) / (maxClo + 1)
        
        //读取设置好的pilist  以后需要动态加载的固定的可以用plist
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)
        
        let composeBtnInfo = NSArray(contentsOfFile: path!)!
        
        for i in 0..<6 {
            
            //几行
            let clo = i % Int(maxClo)
            
            //几列
            let row = i / Int(maxClo)
            
            let btnX = margin + (btnW + margin) * CGFloat(clo)
            
            let btnY = (btnH + margin) * CGFloat(row) + kUIScreenH
            
            let btn = LSPopButton()
            
            btn.frame = CGRectMake(btnX, btnY, btnW, btnH)
            
            //拿到数据
            let dic = composeBtnInfo[i] as! [String : AnyObject]
            
            let icon = dic["icon"] as! String
            let title = dic["title"] as! String
            
            btn.imageView?.image = UIImage(named: icon)
            
            btn.setTitle(title , forState: UIControlState.Normal)
            
            addSubview(btn)
            
            //添加点击事件
            btn.addTarget(self, action: "showDetailVC:", forControlEvents: UIControlEvents.TouchUpInside)
            
            buttons.append(btn)
        }

        
    }
    
    //动画实现
    func show(){
        
        for (index, button) in buttons.enumerate(){
            
//            let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
//            
//            animation.toValue = NSValue(CGPoint: CGPoint(x: button.center.x, y: button.center.y - 300))
//            
//            //速度
//            animation.springSpeed = 10
//            
//            //效果
//            animation.springBounciness = 8
//            
//            //动画开始的时间
//            animation.beginTime = Double(index) * 0.05 + CACurrentMediaTime()
//            
//            //添加到视图
//            button.pop_addAnimation(animation, forKey: nil)
            anim(button, beginTime: CACurrentMediaTime() + Double(index) * 0.04, isUp: true)
        }
        
        
        
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        for (index, button) in buttons.reverse().enumerate() {
            anim(button, beginTime: CACurrentMediaTime() + Double(index) * 0.04, isUp: false)
        }
        
        //执行完成之后删除动画
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            
            self.removeFromSuperview()
        }
    }

    
    // 抽取的时候 第一步1.把要抽取的代码复制过来
    // 2.哪里报错，哪里添加参数
    // 3. 测试
    func anim(button: UIButton,beginTime: Double,isUp: Bool){
        
        let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        if isUp {
            animation.toValue = NSValue(CGPoint: CGPoint(x: button.center.x, y: button.center.y - 300))
        } else {
            
            animation.toValue = NSValue(CGPoint: CGPoint(x: button.center.x, y: button.center.y + 300))
        }
        
        // 弹簧的速度
        animation.springSpeed = 10
        
        // 弹簧的效果
        animation.springBounciness = 8
        // 设置动画开始的时间
        animation.beginTime = beginTime//CACurrentMediaTime() + Double(index) * 0.04
        
        // 添加到视图 - kPOPViewCenter
        button.pop_addAnimation(animation, forKey: nil)
    }
//    //获取当前屏幕截图的方法
//    func getScreenShot() -> UIImage {
//        //1.先获取window
//        let window = UIApplication.sharedApplication().keyWindow
//        
//        //2.开启绘画 这个方法是绘制一个图片  size: 大小  opaue:透明度  scale:缩放
//        UIGraphicsBeginImageContextWithOptions(UIScreen.mainScreen().bounds.size, false, 1)
//        
//        //3.截取到当前窗口的图片  进行绘画
//        window?.drawViewHierarchyInRect(UIScreen.mainScreen().bounds, afterScreenUpdates: false)
//        //4.获取到图片 也就是从当前上下文获取到图片
//        let image = UIGraphicsGetImageFromCurrentImageContext()
//        //5.关闭绘画
//        UIGraphicsEndImageContext()
//        
//        return image
//    }
    
    //点击按钮的方法
    @objc private func showDetailVC(button: LSPopButton){
        
        // 被点击的 放大了， 没有点击的变小了
        //        button.transform = CGAffineTransformm
        // 被点击的放大了，没有被点击的
        
        
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            
            for bt in self.buttons {
                
                bt.alpha = 0
                
                if bt == button {
                    
                    button.transform = CGAffineTransformMakeScale(1.5,1.5)
                    
                    
                } else {
                    
                    bt.transform = CGAffineTransformMakeScale(0.3,0.3)
                    
                    
                }
                
            }
            
            }) { (_) -> Void in
                
                // 当动画完成之后，怎么办 控制器的跳转
                // 视图消失
                self.removeFromSuperview()
                
                // 实际开发过程中，经常用到方法，就是把 控制传递到 view这里，然后进行页面控制器的跳转
                let publish = LSPublishViewController()
                let nav = UINavigationController(rootViewController: publish)
                self.target?.presentViewController(nav, animated: true, completion: nil)
        }
        
        
        
    }

    
    //MARK:-- 懒加载
    lazy var bgImageView: UIImageView = {
        let img = UIImageView()
        
        
        img.image = UIImage.getScreenShot()
        
        
        //毛玻璃效果实现  IOS8之后实现的
        let effect = UIBlurEffect(style: UIBlurEffectStyle.Light)
        
        let effectView = UIVisualEffectView(effect: effect)
        
        //把毛玻璃效果添加都img上
        img.addSubview(effectView)
        
        //毛玻璃需要设置约束
        effectView.snp_makeConstraints(closure: { (make) -> Void in
            make.edges.equalTo(img.snp_edges)
        })
        
        return img
    }()
    
    
}
